package org.dromara.bclt.websocket.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bclt.websocket.domain.ChatMessage;
import org.dromara.bclt.websocket.service.ChatService;
import org.dromara.common.websocket.dto.WebSocketMessageDto;
import org.dromara.common.websocket.utils.WebSocketUtils;
import org.dromara.system.api.model.LoginUser;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collections;

/**
 * 聊天WebSocket处理器
 * 扩展默认WebSocket处理逻辑，处理聊天相关消息
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChatWebSocketHandler {

    private final ChatService chatService;

    /**
     * 订阅聊天消息
     * 此方法会在系统启动时由WebSocketTopicListener调用
     */
    @EventListener
    public void handleChatMessage(WebSocketMessageDto message) {
        log.debug("收到聊天消息: {}", message.getMessage());
        
        try {
            // 尝试解析消息为ChatMessage对象
            if (message.getMessage().contains("\"type\":")) {
                ChatMessage chatMessage = JSONUtil.toBean(message.getMessage(), ChatMessage.class);
                
                // 如果是首次连接消息，可以在这里处理
                if ("connect".equals(chatMessage.getType())) {
                    log.info("用户{}连接到聊天服务", chatMessage.getSenderId());
                    return;
                }
                
                // 处理其他类型的消息，这里直接转发
                chatService.sendMessage(chatMessage);
            }
        } catch (Exception e) {
            log.error("处理聊天消息出错", e);
        }
    }

    /**
     * 发送欢迎消息
     * 
     * @param session WebSocket会话
     * @param loginUser 登录用户
     */
    public void sendWelcomeMessage(WebSocketSession session, LoginUser loginUser) {
        try {
            ChatMessage message = new ChatMessage();
            message.setType("system");
            message.setSenderId(0L);
            message.setSenderName("系统");
            message.setSenderType("system");
            message.setReceiverId(loginUser.getUserId());
            message.setContent("欢迎使用聊天服务!");
            
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(message)));
        } catch (Exception e) {
            log.error("发送欢迎消息失败", e);
        }
    }

    /**
     * 广播系统消息
     * 
     * @param content 消息内容
     */
    public void broadcastSystemMessage(String content) {
        try {
            ChatMessage message = new ChatMessage();
            message.setType("system");
            message.setSenderId(0L);
            message.setSenderName("系统");
            message.setSenderType("system");
            message.setContent(content);
            
            WebSocketUtils.publishAll(JSONUtil.toJsonStr(message));
        } catch (Exception e) {
            log.error("广播系统消息失败", e);
        }
    }
} 